package com.tqw.es.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tqw.entity.Result;
import com.tqw.es.service.impl.ItemServiceImpl;
import com.tqw.item.feign.ItemFeignClient;
import com.tqw.pojo.Item;
import com.tqw.pojo.ItemCat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @author Jim
 */
@Slf4j
@Configuration
public class UpdateIndexCacheTask {
    @Autowired
    private ItemFeignClient itemFeignClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ItemServiceImpl itemService;

    @Async("taskScheduler")
    @Scheduled(cron="0 0 4 * * ?")
    public void updateIndexCache(){
        Result<List<Item>> itemList = itemFeignClient.findItemList();
        Result<List<ItemCat>> itemCatList = itemFeignClient.findItemCatList(1);
        if (itemList.getData().size()>0 && itemCatList.getData().size()>0) {
            ValueOperations<String, String> vo = redisTemplate.opsForValue();
            ObjectMapper objectMapper = new ObjectMapper();
            String json = null;
            try {
                json = objectMapper.writeValueAsString(itemService.handleItemList(itemList, itemCatList));
            } catch (JsonProcessingException e) {
                log.error("com.tqw.es.task.updateIndexCacheTask.executeInternal {} caused by redis serialization exception", e.getMessage());
            }
            vo.set("indexCache", json);
        }
    }
}
